import Config from "@/config"
import { openaiHKAPI } from "@/services/api"
import { ChatCompletionRequest, ChatCompletionResponse } from "@/services/api/types"
import { createOpenAISSEClient } from "@/services/sse"
import type { OpenAISSEClient } from "@/services/sse"

/**
 * 发送普通的聊天完成请求（非流式）
 */
export const sendChatCompletion = async (
  request: ChatCompletionRequest,
): Promise<ChatCompletionResponse> => {
  const response = await openaiHKAPI.post("/v1/chat/completions", request)

  if (response.ok && response.data) {
    return response.data as ChatCompletionResponse
  } else {
    throw new Error(`Chat completion failed: ${response.problem}`)
  }
}

/**
 * 流式聊天完成请求的选项
 */
export interface StreamingChatOptions {
  onMessage?: (content: string) => void
  onComplete?: () => void
  onError?: (error: Error) => void
  onOpen?: () => void
  onClose?: () => void
}

/**
 * 发送流式聊天完成请求
 */
export const sendStreamingChatCompletion = (
  request: Omit<ChatCompletionRequest, "stream">,
  options: StreamingChatOptions = {},
): OpenAISSEClient => {
  const streamingRequest = {
    ...request,
    stream: true,
  }

  const sseClient = createOpenAISSEClient(
    {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${Config.OPENAI_HK_API_KEY}`,
      },
      method: "POST",
      body: streamingRequest,
      timeout: 30000,
      pollingInterval: 0, // 禁用重连，因为这是单次请求
      debug: __DEV__, // 开发模式下启用调试
    },
    {
      onOpen: options.onOpen,
      onMessage: options.onMessage,
      onError: options.onError,
      onComplete: options.onComplete,
      onClose: options.onClose,
    },
  )

  // 立即建立连接
  sseClient.connect()

  return sseClient
}

/**
 * 便捷的流式聊天函数，返回Promise
 */
export const sendStreamingChatCompletionPromise = (
  request: Omit<ChatCompletionRequest, "stream">,
  options: StreamingChatOptions = {},
): Promise<string> => {
  return new Promise((resolve, reject) => {
    const sseClient = sendStreamingChatCompletion(request, {
      ...options,
      onComplete: () => {
        const completeMessage = sseClient.getCompleteMessage()
        options.onComplete?.()
        resolve(completeMessage)
      },
      onError: (error) => {
        options.onError?.(error)
        reject(error)
      },
    })
  })
}
